package com.sniper.utils;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class JavaShellUtil {

    static final Logger LOGGER = LoggerFactory.getLogger(JavaShellUtil.class);
    // 基本路径
    private static final String basePath = "/tmp/";

    // 记录Shell执行状况的日志文件的位置(绝对路径)
    private static final String executeShellLogFile = basePath + "executeShell.log";

    // 发送文件到Kondor系统的Shell的文件名(绝对路径)
    private static final String sendKondorShellName = basePath + "sendKondorFile.sh";

    public static int executeShell(String shellCommand) throws IOException {
        int success;
        StringBuilder stringBuffer = new StringBuilder();
        BufferedReader bufferedReader = null;
        // 格式化日期时间，记录日志时使用
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");

        try {
            stringBuffer.append(dateFormat.format(new Date()))
                    .append("准备执行Shell命令 ").append(shellCommand)
                    .append(" \r\n");

            Process pid;
            String[] cmd = {"/bin/sh", "-c", shellCommand};

            // 执行Shell命令
            ProcessBuilder processBuilder = new ProcessBuilder();
            pid = processBuilder.command(cmd).start();
            stringBuffer.append("进程号：").append(pid.toString()).append("\r\n");
            //bufferedReader用于读取Shell的输出内容
            bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);
            pid.waitFor();

            stringBuffer.append(dateFormat.format(new Date())).append("Shell命令执行完毕\r\n执行结果为：\r\n");
            String line;
            // 读取Shell的输出内容，并添加到stringBuffer中
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line).append("\r\n");
            }

            LOGGER.debug(stringBuffer.toString());
        } catch (Exception ioe) {

            stringBuffer.append("执行Shell命令时发生异常：\r\n").append(ioe.getMessage())
                    .append("\r\n");
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();

                // 将Shell的执行情况输出到日志文件中
                OutputStream outputStream = new FileOutputStream(executeShellLogFile);
                LOGGER.debug(executeShellLogFile);
                try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,
                        "UTF-8")) {
                    outputStreamWriter.write(stringBuffer.toString());
                } catch (Exception e) {
                    LOGGER.debug(e.getMessage());
                    e.printStackTrace();
                }
            }
            success = 1;
        }
        return success;
    }

    /**
     * 存放返回结果
     */
    public static class ShellCommand {
        private Process pid;
        private String command;
        private boolean success;
        private StringBuilder result;
        private Date date = new Date();

        public Process getPid() {
            return pid;
        }

        public void setPid(Process pid) {
            this.pid = pid;
        }

        public String getCommand() {
            return command;
        }

        public void setCommand(String command) {
            this.command = command;
        }

        public boolean isSuccess() {
            return success;
        }

        public void setSuccess(boolean success) {
            this.success = success;
        }

        public StringBuilder getResult() {
            return result;
        }

        public void setResult(StringBuilder result) {
            this.result = result;
        }

        public Date getDate() {
            return date;
        }

        public void setDate(Date date) {
            this.date = date;
        }


        @Override
        public String toString() {
            return "ShellCommand{" +
                    "command='" + command + '\'' +
                    ", success=" + success +
                    ", result='" + result + '\'' +
                    ", date=" + date +
                    '}';
        }
    }

    public static void command(String... command) {
        ProcessBuilder pb;
        String strOut;

        try {
            String[] cmd = {"/bin/sh", "-c", "ls -l"};
            pb = new ProcessBuilder(cmd);
            pb.command(command);
            System.out.println(pb.directory().getAbsolutePath());
            //pb.directory(new File("/Users/suzhen/approot/"));
            pb.redirectErrorStream(true);
            Process pid = pb.start();

//            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(pid.getOutputStream()));
//            bw.write("cd ~/ /r/n");
//            bw.write("ls -l /r/n");
//            bw.flush();

            InputStream is = pid.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                stringBuilder.append(line);
            }
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(br);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws IOException {

        int result = JavaShellUtil
                .executeShell("convert /home/sniper/图片/2015070618434646757.jpg -resize '400x100' /home/sniper/图片/b.jpg");
        System.out.println(result);
    }
}